// editableList.js
'use client';

import React, { Component } from 'react';
import { PlusIcon, ReloadIcon, CheckIcon } from '@radix-ui/react-icons';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable';
import SortableItem from './SortableItem';
import styles from './index.module.scss';
import { plan, updatePlan } from '@/api/ai';
import { connect } from 'react-redux';
import classNames from 'classnames';
import { withConsumer } from '../../../context';

@withConsumer
@connect(({ ppt }) => ({
  selectedModel: ppt.selectedModel,
}))
class EditableList extends Component {
  state = {
    items: [],
    editingId: null,
    show: false,
    isGetData: false,
    state:'',
    plan: {},
    loadingItems: {},  // Track loading state for each item
    completedItems: {}, // Track completed state for each item
    submitLoading: false, // Track submit button loading state
    regenerateLoading: false, // Track regenerate button loading state
  };

  componentDidMount = async () => {
    const {
      value: { setController },
    } = this.props;
    setController('PptOutline', this);
    this.getPlan();
  };

  handleEdit = (id, value) => {
    if (!value || value.trim() === '') {
      this.handleDelete(id);
      return;
    }
    this.setState((prevState) => ({
      items: prevState.items.map((item) =>
        item.id === id ? { ...item, text: value } : item,
      ),
    }));
  };

  handleDelete = (id) => {
    this.setState((prevState) => ({
      items: prevState.items.filter((item) => item.id !== id),
    }));
  };

  handleDragEnd = (event) => {
    const { active, over } = event;
    if (active.id !== over.id) {
      const oldIndex = this.state.items.findIndex(
        (item) => item.id === active.id,
      );
      const newIndex = this.state.items.findIndex(
        (item) => item.id === over.id,
      );
      this.setState((prevState) => ({
        items: arrayMove(prevState.items, oldIndex, newIndex),
      }));
    }
  };

  handleAdd = () => {
    const {
      value: { scrollToBottom }
    } = this.props;

    const newId = `P${this.state.items.length + 1}`;
    this.setState((prevState) => ({
      items: [...prevState.items, { 
        id: newId, 
        text: '',
        need_confirm: false,
        details:'',
      }],
      editingId: newId,
    }),()=>{
      scrollToBottom()
    });
  };
  
  // Set an item to loading state
  setItemLoading = (id, isLoading) => {
    this.setState((prevState) => ({
      loadingItems: {
        ...prevState.loadingItems,
        [id]: isLoading
      }
    }));
  };
  
  // Set an item to completed state
  setItemCompleted = (id, isCompleted) => {
    this.setState((prevState) => ({
      completedItems: {
        ...prevState.completedItems,
        [id]: isCompleted
      }
    }));
  };

  getPlan = async () => {
    const {
      value: { 
        scrollToBottom,
        controller,
      },
    } = this.props;
    const { chatId } = this.props;
    if(!chatId) return 

    var rs = await plan({ conversation_id: chatId });
    if (rs.data?.code == 200 && rs.data.data) {
      var data = rs.data.data;

      var current
      var loadingItems = {}
      var completedItems = {}

      var items = data.steps.map((item,i)=>{
        var id = i+1
        
        // 完成的
        if(i<data.current_step){
          completedItems[id] = id
        }

        // 进行中
        if(i == data.current_step && data.state == 'RUNNING'){
          loadingItems[id] = id
          current = item
        }

        // 结束了
        if(data.state == 'DONE'){
          loadingItems = {}
          completedItems[id] = id
        }

        return {
          ...item,
          id:id,
          text:item.title,
        }
      })

      this.setState({
        plan:data,
        show:true,
        items:items,
        isGetData:true,
        state:data.state,
        loadingItems:loadingItems,
        completedItems:completedItems,
      },()=>{
        scrollToBottom()

        var ChatInput = controller.ChatInput;
        if (ChatInput) {
          ChatInput.setState({disabled:true})
        }

      })

      if(data.state == 'RUNNING'){
        var AIViewer = controller.AIViewer;
        if (AIViewer) {
          AIViewer.setState({
            show: true,
            loading: true,
            length: data.steps.length,
            title: current.title,
            current: data.current_step + 1,
          })
        }
      }

      console.log('plan', data);
    }
  };

  wsSetList = (steps)=>{
    const { value: { scrollToBottom }} = this.props;
    var items = []
    steps.forEach((item,i)=>{
      if(item.title){
        items.push({
          "index": i,
          "text": item.title,
          "details": item.details,
          "need_confirm": false,
          "agent_name": item.agent_name
      })
      }
    })
    console.log(steps)
    this.setState({
      items:items,
      show:true,
    },()=>{
      scrollToBottom()
    })
  }

  submit = async ()=>{
    const { selectedModel } = this.props
    const { items, plan } = this.state;

    // Set loading state for submit button
    this.setState({ submitLoading: true });

    var wsId = window.ws.config.uuid

    var reqData = {
      generator_id: selectedModel,
      "agent_instance_id": plan.agent_instance_id,
      client_id: wsId,
      "is_update" : false,
      "is_replan": false,
      "content": "",
      plan:{
        ...this.state.plan,
      },
    }
    reqData.plan.steps = items.map((item,i)=>{
      var obj = {
        ...item,
        index:i,
        title:item.text,
      }

      delete obj['id']
      delete obj['text']
      return obj
    })

    console.log(reqData)

    try {
      var rs = await updatePlan(reqData);
      if (rs.data?.code == 200) {
        this.getPlan();
      }
    } catch (error) {
      console.error("Error submitting plan:", error);
    } finally {
      this.setState({ submitLoading: false });
    }
  }

  regenerate = async () => {
    const { selectedModel } = this.props
    const { plan } = this.state;

    // Set loading state for regenerate button
    this.setState({ regenerateLoading: true });

    var wsId = window.ws.config.uuid

    var reqData = {
      generator_id: selectedModel,
      "agent_instance_id": plan.agent_instance_id,
      client_id: wsId,
      "is_update" : false,
      "is_replan": true,
      "content": "",
      plan:{
        ...this.state.plan,
      },
    }

    try {
      var rs = await updatePlan(reqData);
      if (rs.data?.code == 200) {
        this.getPlan();
      }
    } catch (error) {
      console.error("Error regenerating plan:", error);
    } finally {
      this.setState({ regenerateLoading: false });
    }
  }

  render() {
    const { state, items, editingId, show, loadingItems, completedItems, submitLoading, regenerateLoading } = this.state;

    var disabled = true
    if(state == 'INITIALIZING') disabled = false
    return (
      <div>
        {show && (
          <div className={styles.container}>
            <DndContext
              collisionDetection={closestCenter}
              onDragEnd={this.handleDragEnd}
            >
              <SortableContext
                items={items}
                strategy={verticalListSortingStrategy}
              >
                <div className={styles.listContainer}>
                  {items.map((item, index) => (
                    <SortableItem
                      key={item.id}
                      id={item.id}
                      index={index}
                      text={item.text}
                      disabled={disabled}
                      onClick={() => this.setState({ editingId: item.id })}
                      isEditing={editingId === item.id}
                      isLoading={loadingItems[item.id]}
                      isCompleted={completedItems[item.id]}
                      onEditStart={() => this.setState({ editingId: item.id })}
                      onEditEnd={(value) => {
                        this.handleEdit(item.id, value);
                        this.setState({ editingId: null });
                      }}
                      onDelete={this.handleDelete}
                    />
                  ))}
                </div>
              </SortableContext>
            </DndContext>
            
            <div className={styles.addButtonContainer}>
              {!disabled && (
                <button 
                  className={styles.addIconBtn} 
                  onClick={this.handleAdd}
                  title="Add item"
                >
                  <PlusIcon style={{ width: 16, height: 16 }}/>
                </button>
              )}
            </div>
            
            {
              !disabled ? (
                <div className={styles.buttonContainer}>
                  <button 
                    className={classNames(styles.addBtn)} 
                    onClick={this.regenerate}
                  >
                    <i className="iconfont icon-shuaxin1"></i>
                    <span>Regenerate</span>
                  </button>

                  <button 
                    className={classNames(styles.addBtn)} 
                    onClick={this.submit}
                  >
                    <i className="iconfont icon-queren"></i>
                    <span>Confirm</span>
                  </button>
                </div>
              ):<div style={{height:'32px'}}></div>
            }
           
          </div>
        )}
      </div>
    );
  }
}

export default EditableList;
